﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;

namespace Paltop_v0._1.UI
{
    public partial class User_Settings : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void AddInfoBtn_Click(object sender, EventArgs e) 
        {
            Paltop_DatabaseLayer.PaltopDatabaseEntities pde = new Paltop_DatabaseLayer.PaltopDatabaseEntities();
            int id = Convert.ToInt32(HttpContext.Current.Session["ACCOUNTID"].ToString());
            if (pde.SuperUsers.Where(p => p.AccountID == id).Count() == 0)
            {//vujud nadashte
                Paltop_DatabaseLayer.SuperUser b = new Paltop_DatabaseLayer.SuperUser();

                b.Name = UserNameTextBox.Text;
                b.Email = EmailTextBox.Text;
                b.Country = CountryTextBox.Text;
                b.Sex = SexTextBox.Text;
                b.ProfilePic = "";
                b.AccountID = Convert.ToInt32(HttpContext.Current.Session["ACCOUNTID"].ToString());

                string date = BirthdayTextBox.Text;//"01/08/2008"
                DateTime dt = Convert.ToDateTime(date);
                b.Birthday = dt;

                pde.SuperUsers.AddObject(b);
                pde.SaveChanges();
            }
            else
            {
                var b = pde.SuperUsers.Where(p => p.AccountID == Convert.ToInt32(HttpContext.Current.Session["ACCOUNTID"].ToString())).Single();


                b.Name = UserNameTextBox.Text;
                b.Email = EmailTextBox.Text;
                b.Country = CountryTextBox.Text;
                b.Sex = SexTextBox.Text;

                string date = BirthdayTextBox.Text;//"01/08/2008"
                DateTime dt = Convert.ToDateTime(date);
                b.Birthday = dt;

                pde.SaveChanges();
            }
        }

        protected void changePassBtn_Click(object sender, EventArgs e)
        {
            int id = Convert.ToInt32(HttpContext.Current.Session["ACCOUNTID"].ToString());

            Paltop_DatabaseLayer.PaltopDatabaseEntities pde = new Paltop_DatabaseLayer.PaltopDatabaseEntities();
            Paltop_.Controllers.UserControler t = new Paltop_.Controllers.UserControler();
            string pass = currentPass.Text;
            pass=t.PasswordHassher(pass);
            var b = pde.Accounts.Where(p => p.Password == pass && p.AccountID == id).FirstOrDefault();//userID ro ham bas check koni yadet nare
            if (b != null)
            {
               
                string s = t.PasswordHassher(newPass.Text);

                if (newPass.Text == confirmNewPass.Text)
                    b.Password = s;
                else
                    doesNotMatchMessage.Text = "two passwords you entered does'nt match!";

                pde.SaveChanges();
            }
            else
                doesNotMatchMessage.Text = "Wrong Password";
        }

        protected void UploadClick(object sender, EventArgs e)
        {
            string sSavePath;
            string sThumbExtension;
            int intThumbWidth;
            int intThumbHeight;

            // Set constant values
            sSavePath = "image/";
            sThumbExtension = "_thumb";
            intThumbWidth = 160;
            intThumbHeight = 120;
            // HtmlInputFile MyFile1 = (HtmlInputFile)(Page.FindControl("filUpload"));


            // If file field isn’t empty
            if (uploadProfilePic.PostedFile != null)
            {
                // Check file size (mustn’t be 0)
                HttpPostedFile myFile = uploadProfilePic.PostedFile;
                int nFileLen = myFile.ContentLength;
                if (nFileLen == 0)
                {
                    lblOutput.Text = "No file was uploaded.";
                    return;
                }

                // Check file extension (must be JPG)
                if (System.IO.Path.GetExtension(myFile.FileName).ToLower() != ".jpg")
                {
                    lblOutput.Text = "The file must have an extension of JPG";
                    return;
                }

                // Read file into a data stream
                byte[] myData = new Byte[nFileLen];
                myFile.InputStream.Read(myData, 0, nFileLen);

                // Make sure a duplicate file doesn’t exist.  If it does, keep on appending an 
                // incremental numeric until it is unique
                string sFilename = System.IO.Path.GetFileName(myFile.FileName);
                int file_append = 0;
                while (System.IO.File.Exists(Server.MapPath(sSavePath + sFilename)))
                {
                    file_append++;
                    sFilename = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName)
                                     + file_append.ToString() + ".jpg";
                }

                // Save the stream to disk
                System.IO.FileStream newFile
                        = new System.IO.FileStream(Server.MapPath(sSavePath + sFilename),
                                                   System.IO.FileMode.Create);
                newFile.Write(myData, 0, myData.Length);
                newFile.Close();

                // Check whether the file is really a JPEG by opening it
                System.Drawing.Image.GetThumbnailImageAbort myCallBack =
                               new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
                Bitmap myBitmap;
                try
                {
                    myBitmap = new Bitmap(Server.MapPath(sSavePath + sFilename));

                    // If jpg file is a jpeg, create a thumbnail filename that is unique.
                    file_append = 0;
                    string sThumbFile = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName)
                                                             + sThumbExtension + ".jpg";
                    while (System.IO.File.Exists(Server.MapPath(sSavePath + sThumbFile)))
                    {
                        file_append++;
                        sThumbFile = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName) +
                                       file_append.ToString() + sThumbExtension + ".jpg";
                    }

                    // Save thumbnail and output it onto the webpage
                    System.Drawing.Image myThumbnail
                            = myBitmap.GetThumbnailImage(intThumbWidth,
                                                         intThumbHeight, myCallBack, IntPtr.Zero);
                    myThumbnail.Save(Server.MapPath(sSavePath + sThumbFile));
                    imgPicture.ImageUrl = sSavePath + sThumbFile;

                    // Displaying success information
                    lblOutput.Text = "File uploaded successfully!";
                    //  myFile.SaveAs("\\image");


                    // Destroy objects
                    myThumbnail.Dispose();
                    myBitmap.Dispose();
                }
                catch (ArgumentException errArgument)
                {
                    // The file wasn't a valid jpg file
                    lblOutput.Text = "The file wasn't a valid jpg file.";
                    System.IO.File.Delete(Server.MapPath(sSavePath + sFilename));
                }
            }
        }

        protected void Button1_Click1(object sender, EventArgs e)
        {

        }
        public bool ThumbnailCallback()
        {
            return false;
        }  

    }
}